#include "StudentList.h"
#include <iostream>
using namespace std;

int main() {
    StudentLinkedList list;
    bool isQuit = false;
    int option;

    cout << "欢迎访问学生信息系统，请登录...\n";
    while (!isQuit) {
        cout << "\n====学生信息管理系统====\n";
        cout << "**********1.学生信息查询**********\n";
        cout << "**********2.学生信息添加**********\n";
        cout << "**********3.学生信息修改**********\n";
        cout << "**********4.学生信息删除**********\n";
        cout << "**********5.保存信息到文件**********\n"; 
        cout << "**********6.从文件加载信息**********\n"; 
        cout << "**********0.退出**********\n";
        cout << "请选择...";
        cin >> option;

        // 处理输入类型错误
        while (cin.fail()) {
            cin.clear();
            cin.ignore(1024, '\n');
            cout << "输入类型错误，请重新输入...\n";
            cin >> option;
        }

        switch (option) {
        case 0:
            isQuit = true;
            break;
        case 1:
            list.displayAll();
            break;
        case 2: {
            int count;
            cout << "请输入要添加的学生数量：";
            cin >> count;
            // 处理无效输入（非正整数）
            while (cin.fail() || count <= 0) {
                cin.clear(); // 清除输入错误标记
                cin.ignore(1024, '\n'); // 清空无效输入
                cout << "输入无效！请输入正整数：";
                cin >> count;
            }
            // 循环录入指定数量的学生信息
            for (int i = 0; i < count; i++) {
                int id; string name, major; int age;
                cout << "请输入第" << (i + 1) << "个学生的学号、姓名、年龄、专业：";
                cin >> id >> name >> age >> major;
                list.insertAtTail(id, name, age, major); // 调用尾插法添加
            }
            cout << "已成功添加" << count << "名学生！\n";
            break;
        }
        case 3: {
            int id;
            cout << "请输入要修改的学号：";
            cin >> id;
            StudentNode* node = list.findByID(id);
            if (node) {
                cout << "请输入新姓名、年龄、专业：";
                cin >> node->name >> node->age >> node->major;
                cout << "修改成功！\n";
            }
            else {
                cout << "未找到该学生！\n";
            }
            break;
        }
        case 4: {
            int id;
            cout << "请输入要删除的学号：";
            cin >> id;
            list.deleteByID(id);
            break;
        }
        case 5:
            list.saveToFile("student_info.txt"); // 调用保存方法，文件名固定为student_info.txt
            break;
        case 6:
            list.loadFromFile("student_info.txt"); // 调用加载方法，对应上述文件名
            break;
        default:
            cout << "输入错误，请重试...\n";
            break;
        }
    }
    return 0;
}